The for statement executes the code in the braces for a known number of times. Usually, the for statement is used to iterate over arrays.
General syntax:
for(initial_value_for_a_counter_variable; stop_contidion_for_counter_variable; increment_decrement_counter_variable)
{
Execute all statements inside the braces
}
Practical example:
In the following example, we store six numbers from lottery in a standard vector and iterate over the vector using a for statement to display the numbers.
#include <iostream>
#include <vector>
int main()
{
//we have a standard vector of integers in which we want to store the numbers from the lottery.
std::vector<int> lotteryNumbers;
//we add the numbers in the vector
lotteryNumbers.push_back(5);
lotteryNumbers.push_back(39);
lotteryNumbers.push_back(10);
lotteryNumbers.push_back(21);
lotteryNumbers.push_back(1);
lotteryNumbers.push_back(40);
//we use a for statement to show the numbers from the vector.
std::cout << "The numbers from the lottery are: ";
for(unsigned int i = 0; i < lotteryNumbers.size(); i++)
{
std::cout << lotteryNumbers.at(i) << " ";
}
return 0;
}
Note: If the size of the vector would be zero, the for statement would not be executed
In a for statement, any condition can be omitted but it must exist somewhere else in order to have the same behavior.
#include <iostream>
int main()
{
int n = 0;
for(; n < 10; n++)
{
//execute statements
}
}
#include <iostream>
int main()
{
int n = 0;
for(; n < 10;)
{
//execute statements
n++;
}
}
#include <iostream>
int main()
{
int n = 0;
for(;;)
{
if(n >= 10)
{
break;
}
else
{
n++;
}
}
}
All three examples produce the same output.